<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/8/4
 * Time: 13:45
 */

namespace Admin\Controller;


class AdcodetemplateController extends AdminController
{
    public function _myinitialize()
    {
        $this->db = M('ad_code_template');
        $this->select = array("js", "json", "html");
        $this->username = session('user_auth.username');
    }

    //广告模板列表
    public function lst()
    {
        $where = array(
            'status' => 1,
        );
        $lists = $this->db->where($where)->order("update_time desc")->select();
        $this->assign('lists', $lists);
        $this->display();
    }

    //广告模板新增
    public function add()
    {
        if (IS_POST) {
            $data = $this->db->create();
            if ($data === false) {
                $this->error($this->db->getError());
            } else {
                $data['update_user'] = $this->username;
                $data['update_time'] = time();
            }
            $rid = $this->db->add($data);
            if ($rid === false) {
                $this->error($this->db->getDbError());
            }
            $this->redirect('lst');
        } else {
            $this->assign('types', $this->select);
            $this->assign('istype', "add");
            $this->display();
        }
    }

    //广告模板编辑
    public function edit()
    {
        if (IS_POST) {
            $data = $this->db->create();
            if ($data === false) {
                $this->error($this->db->getError());
            } else {
                $data['update_user'] = $this->username;
                $data['update_time'] = time();
            }
            $rid = $this->db->save($data);
            if ($rid === false) {
                $this->error($this->db->getDbError());
            }
            $this->redirect('lst');
        } else { //回显
            $id = I('id');
            $data = $this->db->where(array('id' => $id))->find();
            $this->assign('types', $this->select);
            $this->assign('data', $data);
            $this->assign('istype', "edit");
            $this->display("add");
        }
    }

    //广告模板删除
    public function del()
    {
        $id = I('id');
        if (!empty($id)) {
            //根据模板id去广告表中查是否有广告在使用本模板 ，如果有则不能删除
            $count=M('ad')->where(array("template_id"=>$id,"status"=>1))->count('id');
            if($count > 0){
                $this->error("该模板被".$count."条广告使用，无法删除",$_SERVER["HTTP_REFERER"]);
            }else{
                $data = array(
                    'status' => 0,
                    'update_time' => time(),
                    'update_user' => $this->username,
                );
                $this->db->where(array('id' => $id))->save($data);
                $this->redirect('lst');
            }
        }
    }
}